package com.zhf.servlet;

import com.zhf.bean.Student;
import com.zhf.service.StudentService;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author: ZhaoHuanfeng
 * @Date: 2020/10/17 19:59
 */
@WebServlet(name = "AddStudentServlet",urlPatterns = "/addstudent")
public class AddStudentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        request.setCharacterEncoding("utf-8");
        String studentID = (String)request.getParameter("studentID");
        String stuname = (String)request.getParameter("stuname");
        String sex = (String)request.getParameter("sex");
        String birthday = (String)request.getParameter("birthday");
        String email = (String)request.getParameter("email");
        String remark = (String)request.getParameter("remark");
        String stuclass = (String)request.getParameter("stuclass");
        Student newStudent=new Student(stuname,studentID,sex,birthday,email,remark,stuclass);
        StudentService studentService = new StudentService();
        //判断该学生是否存在
        if (!studentService.isStudentID(studentID)){
            //不存在则添加
            boolean b = studentService.addStudent(newStudent);
            //将修改结果写入request转发到该页面返回
            request.setAttribute("result", b ? "seccess" : "fail");
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("addstudent.jsp");
            requestDispatcher.forward(request,response);

        }else {
            //服务器跳转request共享
            request.setAttribute("error","studenterror");
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("addstudent.jsp");
            requestDispatcher.forward(request,response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
